﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Objects;

namespace InfoMap.DataAccess
{
    public class Repository<T> where T : class
    {
        private ObjectContext context {get;set;}
        private ObjectSet<T> dbSet { get; set; }


        public Repository()
        {
            this.context = getFromState();
            this.dbSet = context.CreateObjectSet<T>();
        }

        private ObjectContext getFromState()
        {
            return StateProvider.Get<ISessionProvider>("SessionProvider").CreateContext();
        }
        
        public virtual IEnumerable<T> Get(
            Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<T> query = dbSet;
            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split(
                new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual void Insert(T entity)
        {
            dbSet.AddObject(entity);
        }

        public virtual void Delete(T entity)
        {
            dbSet.DeleteObject(entity);
        }

        public void Update(T entity)
        {
            dbSet.Attach(entity);            
        }

        public void SaveChanges()
        {
            context.SaveChanges();            
        }
    }
}
